
#pragma once

#ifndef _base_memory_gpool_h_
#define _base_memory_gpool_h_

#include "base.config.h"


PP_BEGIN_BASE


template < typename T >
class memory_pool
{

public:
	static void* operator new( size_t len_ )
	{
// 		if( sizeof(T) == len_ )
// 			return 0;
//  
// 		if( sizeof(T) >= sizeof(ub8) )
// 			return 0;

		if( !_gp )
			alloc();

		ub1* rp = _gp;
		_gp = *reinterpret_cast<ub1**>(rp);

		return rp;
	}

	static void operator delete( void* dp_ )
	{
		*reinterpret_cast<ub1**>(dp_) = _gp;
		_gp = static_cast<ub1*>(dp_);
	}
	
private:

	enum
	{
		ALLOC_BLOCK_SIZE = 50,
	};

	static void alloc()
	{
		_gp = new ub1[sizeof(T) * ALLOC_BLOCK_SIZE];

		ub1** cur = reinterpret_cast<ub1**>(_gp);
		ub1* next = _gp;

		int a = sizeof(T);

		for( size_t i = 0; i < ALLOC_BLOCK_SIZE; i++ )
		{
			next += sizeof(T);
			*cur = next;
			cur = reinterpret_cast<ub1**>(next);
		}

		*cur = 0;

	}

	static ub1* _gp;

protected:
	~memory_pool() 
	{
		ub1** p = reinterpret_cast<ub1**>(_gp);
		::delete *p;
	}

};

template< typename T >
ub1* memory_pool<T>::_gp;

PP_END_BASE

#endif